package ee.serge.server;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.JDOException;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import ee.serge.service.PublicService;
import ee.serge.shared.BusinessException;
import ee.serge.shared.Feedback;
import ee.serge.shared.HandledException;
import ee.serge.shared.IP;
import ee.serge.shared.Loan;
import ee.serge.shared.NotFoundException;

@SuppressWarnings("serial")
public class PublicServiceImpl extends RemoteServiceServlet implements PublicService {

   @Override
   public List<Loan> getLoans() throws HandledException {
      PersistenceManager pm = PMF.get().getPersistenceManager();
      List<Loan> returnLoans = new ArrayList<Loan>();
      try {
         Query query = pm.newQuery(Loan.class);
         query.setFilter("active == true");
         query.setOrdering("apr asc");
         List<Loan> loans = (List<Loan>) query.execute();
         loans.size();
         for (Loan loan : loans) {
            returnLoans.add(loan);
         }
         return returnLoans;
      } catch (Exception e) {
         System.out.println(e);
         throw new BusinessException("System error.");
      } finally {
         pm.close();
      }
   }

   @Override
   public Loan getLoan(long id) throws HandledException {
      PersistenceManager pm = PMF.get().getPersistenceManager();
      try {
         Loan loan = pm.getObjectById(Loan.class, id);
         if (!loan.isActive()) throw new NotFoundException();
         pm.close();
         loan.setFeedbackList(getFeedbackList(loan.getKey()));
         return loan;
      } catch (Exception e) {
         throw new NotFoundException();
      }
   }

   @Override
   public void addFeedback(Feedback feedback, String challenge, String response) throws HandledException {
      if (!verifyChallenge(challenge, response)) {
      	throw new BusinessException("Invalid captcha");
      }
      PersistenceManager pm = PMF.get().getPersistenceManager();
      try {
         Object o = pm.getObjectById(IP.class, getThreadLocalRequest().getRemoteAddr());
         if (o != null) {
            throw new BusinessException("You are banned, you cannot post a review.");
         }
      } catch (JDOException e) {}
      try {
         feedback.setIpAddress(getThreadLocalRequest().getRemoteAddr());
         if (feedback.getCreationTime() == 0) {
         	feedback.setCreationTime(System.currentTimeMillis());
         }
         pm.makePersistent(feedback);
         Loan loan = pm.getObjectById(Loan.class, feedback.getLoanKey());
         loan.increaseFeedbackCount();
         loan.increaseTotalRating(feedback.getRating());
      } catch (JDOException e) {
         throw new BusinessException("Error submitting review.");
      } finally {
         pm.close();
      }
   }

   @Override
   public boolean verifyChallenge(String challenge, String response) {
      return true;
   }

   @Override
   public List<Feedback> getFeedbackList(String loanKey) throws HandledException {
      PersistenceManager pm = PMF.get().getPersistenceManager();
      List<Feedback> returnList = new ArrayList<Feedback>();
      try {
         Query query = pm.newQuery(Feedback.class);
         query.setFilter("loanKey == A");
         query.setOrdering("creationTime desc");
         query.declareParameters("String A");
         List<Feedback> feedbacklist = (List<Feedback>) query.execute(loanKey);
         for (Feedback val : feedbacklist) {
            returnList.add(val);
         }
         return returnList;
      } catch (Exception e) {
         System.out.println(e);
         throw new BusinessException("System error.");
      } finally {
         pm.close();
      }
   }
}
